package com.example.util;

import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

public class PhotoUtil {

    static BufferedImage bfImage = null;
    static int width = 0;
    static int height = 0;

    /**
     * @param imgStr base64编码字符串
     * @param path   图片路径-具体到文件
     * @return
     * @Description: 将base64编码字符串转换为图片
     * @Author:
     * @CreateTime:
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获得图片的像素
     *
     * @return
     */
    public static int[][] getPhotopix(File img) {

        try {
            bfImage = ImageIO.read(img);
        } catch (IOException e) {
            e.printStackTrace();
        }

        width = bfImage.getWidth();
        height = bfImage.getHeight();

//        int num = Math.max(width, height);
        int[][] imgData = new int[width][height];
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                imgData[i][j] = bfImage.getRGB(i, j);
            }
        }
        return imgData;
    }

    /**
     * 将图片转成黑白的方法
     *
     * @param img
     */
    public static String changeColor(File img,String afterPath) throws IOException {
        int[][] imgData = getPhotopix(img);
        Graphics bg = bfImage.getGraphics();

        int width = bfImage.getWidth();
        int height = bfImage.getHeight();

        System.out.println(imgData.length);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Color color = new Color(imgData[i][j]);
                int red = color.getRed();
                int blue = color.getBlue();
                int green = color.getGreen();

                int avg = (Math.max(Math.max(red, blue), green) + Math.min(Math.min(red, blue), green)) / 2;
                Color newColor = new Color(avg, avg, avg);
                bfImage.setRGB(i, j, newColor.getRGB());
            }
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        System.out.println(uuid);
        String path=afterPath + uuid + ".jpg";
        File outputFile = new File(path);
        ImageIO.write(bfImage,"jpg",outputFile);
        return path;

    }

    public static void reduceImg(String imgSrc, String imgDist, int widths, int highest, Float rate) {
        try {
            File srcfile = new File(imgSrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            // 如果比例不为空则说明是按比例压缩
            if (rate != null && rate > 0) {
                //获得源图片的宽高存入数组中
                int[] results = getImgWidthHeight(srcfile);
                if (results == null || results[0] == 0 || results[1] == 0) {
                    return;
                } else {
                    //按比例缩放或扩大图片大小，将浮点型转为整型
                    widths = (int) (results[0] * rate);
                    highest = (int) (results[1] * rate);
                }
            }
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widths, (int) highest, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本，返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widths, highest, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            String formatName = imgDist.substring(imgDist.lastIndexOf(".") + 1);
            ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */ , new File(imgDist)  /* target */ );
        } catch (Exception ef) {
            ef.printStackTrace();
        }
    }
    /**
     * 获取图片宽度和高度
     *
     * @param
     * @return 返回图片的宽度
     */
    public static int[] getImgWidthHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = { 0, 0 };
        try {
            // 获得文件输入流
            is = new FileInputStream(file);
            // 从流里将图片写入缓冲图片区
            src = ImageIO.read(is);
            result[0] =src.getWidth(null); // 得到源图片宽
            result[1] =src.getHeight(null);// 得到源图片高
            is.close();  //关闭输入流
        } catch (Exception ef) {
            ef.printStackTrace();
        }

        return result;
    }
    public  static  String download(MultipartFile img) throws IOException {
        String path="src/main/resources/static/oldPhoto/";//上传图片目录
        String filename =img.getOriginalFilename();
        //把文件的名称设置唯一值:UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        File image = new File(path,filename);
        img.transferTo(image);
        String photoUrl = path + filename;//上传图片的地址
        return  photoUrl;
    }
}
